/**
 * axios 二次封装
 *
 * @author jinzhengze
 */

import axios from 'axios'

axios.requests = []
axios.defaults.baseURL = import.meta.env.MODE === 'development' ? '/api' : ''
axios.defaults.timeout = 60000
axios.defaults.withCredentials = false
axios.defaults.headers['Content-Type'] = 'application/json;charset=UTF-8'

/**
 * 请求拦截器
 */
axios.interceptors.request.use(req => {
    const source = axios.CancelToken.source()
    req.cancelToken = source.token
    axios.requests.length > 64 && axios.requests.shift()
    axios.requests['push'](source)
    return req
}, err => Promise.reject(err))

/**
 * 文件上传函数
 */
axios.upload = function (option) {
    !option.headers && (option.headers = {})
    option.headers['Content-Type'] = 'multipart/form-data'
    option.transformRequest = [data => {
        let formData = new FormData()
        for(let key in data)
            formData.append(key, data[key])
        return formData
    }]
    return axios(option)
}

export default axios
